package com.hxzy.research.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //效验登录获取登录的url
        String url=httpServletRequest.getRequestURI();
        //实际应用中我们的公开地址可能是配置在配置文件中，我们现在就确定一个就可以了
        //判断url是否是公开地址，这里就是登录的提交地址
        if (url.indexOf("userLogin.go")>=0){ //包括了userLogin.action
            //放行
            return true;
        }
        //判断session
        HttpSession session=httpServletRequest.getSession();
        String username=(String)session.getAttribute("username");
        if (username!=null){
            //身份存在，放行
            return true;
        }
        //设置绝对路径
        String basePath = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + ":" +
                httpServletRequest.getServerPort()  + httpServletRequest.getContextPath();
        //代码执行到这个地方，表示用户需要身份验证，跳转到登录页面
        httpServletResponse.sendRedirect(basePath + "/login.jsp");
        //httpServletRequest.getRequestDispatcher(basePath +"/login.jsp").forward(httpServletRequest,httpServletResponse);
        return false;




    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
